import { createApp, h, ref } from 'vue';
import Modal from '@components/Modal.vue';

export function createModal() {
  // 全局实例存储
  const instances = [];
  
  // 主函数
  function modal(options = {}) {
    const container = document.createElement('div');
    document.body.appendChild(container);
    
    const visible = ref(true);
    
    const app = createApp({
      setup() {
        const onClose = () => {
          visible.value = false;
          setTimeout(() => {
            app.unmount();
            container.remove();
            const index = instances.findIndex(instance => instance === app);
            if (index !== -1) {
              instances.splice(index, 1);
            }
          }, 300); // 给过渡动画留时间
        };
        
        return () => h(Modal, {
          modelValue: visible.value,
          'onUpdate:modelValue': (val) => {
            visible.value = val;
            if (!val) onClose();
          },
          onConfirm: () => {
            if (options.onConfirm) options.onConfirm();
            onClose();
          },
          onCancel: () => {
            if (options.onCancel) options.onCancel();
            onClose();
          },
          ...options
        }, options.slots || {});
      }
    });
    
    instances.push(app);
    app.mount(container);
    
    return {
      close: () => {
        visible.value = false;
      }
    };
  }
  
  // 预设类型,作为属性附加给modal函数
  modal.alert = (content, title = '提示', onConfirm) => {
    return modal({
      title,
      content,
      showCancel: false,
      onConfirm
    });
  };
  
  modal.confirm = (content, title = '确认', onConfirm, onCancel) => {
    return modal({
      title,
      content,
      onConfirm,
      onCancel
    });
  };
  
  // 关闭所有弹窗
  modal.closeAll = () => {
    instances.forEach(instance => {
      const vm = instance._instance.subTree.component.ctx;
      if (vm?.close) vm.close();
    });
  };
  
  return modal;
}

export default {
  install(app) {
    const modal = createModal();
    app.config.globalProperties.$modal = modal;
    app.provide('modal', modal);
  }
};
